let log4js = require('log4js');
let {app, BrowserWindow} = require('electron');
let http = require('./libraries/http');
let cnblogsApi = require('./cnblogsApi');
let file =require('./file');

const clientId = '0e72d244-7e20-496a-aabc-2fa85c1d909c';
const clientSecret = 'uHWWIabipHbA1K5JjMrB4JGyBhWfU-IyKdRZV4fOoGe5Q_EjWoKywSn4Ttp8wQkmpZYZb_0q3q8wENFy';

let mainWin = null;
let loginWin = null;

let token = null;
let myInfo = null;

let firstLoad = true;
let logger = initLogger();

app.on('ready', () => {
    loginWin = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        },
        show: false
    });

    mainWin = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        },
        show: false
    }); 
    
    mainWin.maximize();  
    
    mainWin.once('ready-to-show', ()=>{
        mainWin.show();
        firstLoad = false;
    }); 
    
    mainWin.on('closed', ()=>{
        app.quit();
    });

    token = file.loadTokenFromFile();

    if(!token){
        login(response=>{
            file.saveToken2File(response);
            var obj = JSON.parse(response);
            token = obj.access_token;
            myInfo = loadMyInfoFromCnblogs();
            showMainWin();
        });
    }else{
        showMainWin();
        myInfo = file.loadMyInfoFromFile();
    }

});

function showMainWin(){
    mainWin.loadFile('./app/index.html');
    if(!firstLoad){
        mainWin.show();
    }
}

function login(afterLogin){   
    loginWin.show();
    loginWin.webContents.loadURL('https://oauth.cnblogs.com/connect/authorize?client_id=0e72d244-7e20-496a-aabc-2fa85c1d909c&scope=openid profile CnBlogsApi&response_type=code id_token&redirect_uri=https://oauth.cnblogs.com/auth/callback&state=cnblogs.com&nonce=cnblogs.com');
    loginWin.webContents.on('did-redirect-navigation', (event, url) => {
        if(url.startsWith('https://oauth.cnblogs.com/auth/callback#code=')){
            var code = url.substr(45, 64);
            var data = {
                'client_id': clientId,
                'client_secret': clientSecret,
                'grant_type': 'authorization_code',
                'redirect_uri': 'https://oauth.cnblogs.com/auth/callback',
                'code': code
            };
            
            http.post('https://oauth.cnblogs.com/connect/token', null, data, function(response){
                afterLogin(response);
                loginWin.hide();
            }, function(error){
                logger.error(error);
            })
        }
    });
}

function initLogger() {
    log4js.configure({
        appenders: { runtime_log: { type: 'file', filename: 'files/runtime.log' } },
        categories: { default: { appenders: ['runtime_log'], level: 'error' } }
    });

    let logger = log4js.getLogger('runtime_log');
    return logger;
}

function loadMyInfoFromCnblogs(){
    cnblogsApi.getMyInfo(token, model=>{
        myInfo = model;
        file.saveMyInfo2File(myInfo);
    }, error=>logger.error(error))
}


/*************************
 * 以下函数供渲染线程调用
 ************************/

// 加载数据
const loadContents = function(type, pageIndex, pageSize, whenDone){
    cnblogsApi.getContents(token, type, pageIndex, pageSize, contents => whenDone(contents), error => logger.error(error));
}

// 加载评论
const loadComments = function(id, whenDone){
    cnblogsApi.getComments(token, id, myInfo, comments => whenDone(comments), error => logger.error(error));
}

// 发送文字
const send = function(content, whenDone, whenError){
    cnblogsApi.send(token, content, res => whenDone(res), error => {
        whenError(error);
        logger.error(error);
    });
}

exports.loadContents = loadContents;
exports.loadComments = loadComments;
exports.send = send;
